import csv
import io
import chardet
from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from libs.check_alarm import render_alarm_template
from libs.conn import *
from libs.utils import *

alarm_plans_bp = Blueprint('alarm_plans', __name__)

@alarm_plans_bp.route('/api/get_alarm_plans', methods=['GET'])
@jwt_required()
def get_alarm_plans():
    client_id = request.args.get('client_id')
    plan_name = request.args.get('plan_name')
    plan_enable = request.args.get('plan_enable')
    plan_noticetype = request.args.get('plan_noticetype')
    page_size = int(request.args.get('page_size'))
    page_current = int(request.args.get('page_current'))
    sql = "FROM alarm_plans WHERE 1=1"
    params = []
    if client_id != None and client_id != '':
        sql += " AND client_id = ?"
        params.append(client_id)
    if plan_name != None and plan_name != '':
        sql += " AND plan_name LIKE ?"
        params.append('%' + plan_name + '%')
    if plan_enable != None and plan_enable != '':
        sql += " AND plan_enable = ?"
        params.append(plan_enable)
    if is_string_valid(plan_noticetype):
        sql += " AND plan_noticetype like ?"
        params.append('%' + plan_noticetype + '%')
    offset = (page_current - 1) * page_size
    rows = fetchall("SELECT * " + sql + " ORDER BY plan_id DESC LIMIT ?, ?", tuple(params + [offset, page_size]))
    total_count = fetchvalue("SELECT COUNT(*) " + sql, tuple(params))
    return { 'status': 'ok', 'data': rows, 'page_total': total_count }

@alarm_plans_bp.route('/api/get_client_alarm_plans', methods=['POST'])
@jwt_required()
def get_client_alarm_plans():
    client_id = request.json.get('client_id')
    rows = fetchall("SELECT * FROM alarm_plans WHERE client_id = ?", (client_id,))
    return { 'status': 'ok', 'data': rows }

@alarm_plans_bp.route('/api/add_alarm_plan', methods=['POST'])
@jwt_required()
def add_alarm_plan():
    client_id = request.json.get('client_id')
    plan_name = request.json.get('plan_name')
    plan_maxtime = int(request.json.get('plan_maxtime'))
    plan_rangetime = int(request.json.get('plan_rangetime'))
    plan_maxcount = int(request.json.get('plan_maxcount'))
    plan_begintime = request.json.get('plan_begintime')
    plan_endtime = request.json.get('plan_endtime')
    plan_template = request.json.get('plan_template')
    if plan_maxtime <= 0 and plan_maxcount <= 0:
        return { 'status': 'error', 'data': '请至少选择一种报警方式' }
    plan_id = execute("INSERT INTO alarm_plans (client_id, plan_name, plan_maxtime, plan_rangetime, plan_maxcount, plan_begintime, plan_endtime, plan_template, plan_noticetype) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", (client_id, plan_name, plan_maxtime, plan_rangetime, plan_maxcount, plan_begintime, plan_endtime, plan_template, ''))
    return { 'status': 'ok', 'data': plan_id }

@alarm_plans_bp.route('/api/add_batch_alarm_plan', methods=['POST'])
@jwt_required()
def add_batch_alarm_plan():
    client_ids = request.json.get('client_ids')
    plan_name = request.json.get('plan_name')
    plan_maxtime = int(request.json.get('plan_maxtime'))
    plan_rangetime = int(request.json.get('plan_rangetime'))
    plan_maxcount = int(request.json.get('plan_maxcount'))
    plan_begintime = request.json.get('plan_begintime')
    plan_endtime = request.json.get('plan_endtime')
    plan_template = request.json.get('plan_template')
    if plan_maxtime <= 0 and plan_maxcount <= 0:
        return { 'status': 'error', 'data': '请至少选择一种报警方式' }
    plan_enable = int(request.json.get('plan_enable'))
    # plan_noticetype = request.json.get('plan_noticetype')
    plan_email = int(request.json.get('plan_email'))
    plan_sms = int(request.json.get('plan_sms'))
    # plan_wechat = int(request.json.get('plan_wechat'))
    # plan_dingtalk = int(request.json.get('plan_dingtalk'))
    success_count = 0
    plan_noticetype = []
    if plan_email == 1:
        plan_noticetype.append('email')
    if plan_sms == 1:
        plan_noticetype.append('sms')
    # if plan_wechat == 1:
    #     plan_noticetype.append('wechat')
    # if plan_dingtalk == 1:
    #     plan_noticetype.append('dingtalk')
    plan_noticetype = ','.join(plan_noticetype)
    for client_id in client_ids:
        row = fetchone("SELECT * FROM clients WHERE client_id = ?", (client_id,))
        if row == None:
            continue
        plan_id = execute("INSERT INTO alarm_plans (client_id, plan_name, plan_maxtime, plan_rangetime, plan_maxcount, plan_enable, plan_noticetype, plan_begintime, plan_endtime, plan_template, plan_noticetype) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (client_id, plan_name, plan_maxtime, plan_rangetime, plan_maxcount, plan_enable, plan_noticetype, plan_begintime, plan_endtime, plan_template, plan_noticetype))
        success_count += 1
    return { 'status': 'ok', 'data': success_count }

@alarm_plans_bp.route('/api/update_alarm_plan', methods=['POST'])
@jwt_required()
def update_alarm_plan():
    plan_id = request.json.get('plan_id')
    plan_name = request.json.get('plan_name')
    plan_maxtime = int(request.json.get('plan_maxtime'))
    plan_rangetime = int(request.json.get('plan_rangetime'))
    plan_maxcount = int(request.json.get('plan_maxcount'))
    plan_begintime = request.json.get('plan_begintime')
    plan_endtime = request.json.get('plan_endtime')
    plan_template = request.json.get('plan_template')
    if plan_maxtime <= 0 and plan_maxcount <= 0:
        return { 'status': 'error', 'data': '请至少选择一种报警方式' }
    execute("UPDATE alarm_plans SET plan_name = ?, plan_maxtime = ?, plan_rangetime = ?, plan_maxcount = ?, plan_begintime = ?, plan_endtime = ?, plan_template = ? WHERE plan_id = ?", (plan_name, plan_maxtime, plan_rangetime, plan_maxcount, plan_begintime, plan_endtime, plan_template, plan_id))
    return { 'status': 'ok', 'data': 'success' }

@alarm_plans_bp.route('/api/alarm_plan_enable', methods=['POST'])
@jwt_required()
def alarm_plan_enable():
    plan_id = request.json.get('plan_id')
    plan_enable = int(request.json.get('plan_enable'))
    execute("UPDATE alarm_plans SET plan_enable = ? WHERE plan_id = ?", (plan_enable, plan_id))
    return { 'status': 'ok', 'data': 'success' }

@alarm_plans_bp.route('/api/alarm_plan_sms', methods=['POST'])
@jwt_required()
def alarm_plan_sms():
    plan_id = request.json.get('plan_id')
    plan_sms = int(request.json.get('plan_sms'))
    plan_noticetype = fetchvalue("SELECT plan_noticetype FROM alarm_plans WHERE plan_id = ?", (plan_id,))
    plan_noticetypes = []
    if is_string_valid(plan_noticetype):
        plan_noticetypes = plan_noticetype.split(',')
    if plan_sms == 1 and 'sms' not in plan_noticetypes:
        plan_noticetypes.append('sms')
    elif plan_sms == 0 and 'sms' in plan_noticetypes:
        plan_noticetypes.remove('sms')
    plan_noticetype = ','.join(plan_noticetypes)
    execute("UPDATE alarm_plans SET plan_noticetype = ? WHERE plan_id = ?", (plan_noticetype, plan_id))
    return { 'status': 'ok', 'data': 'success' }

@alarm_plans_bp.route('/api/alarm_plan_email', methods=['POST'])
@jwt_required()
def alarm_plan_email():
    plan_id = request.json.get('plan_id')
    plan_email = int(request.json.get('plan_email'))
    plan_noticetype = fetchvalue("SELECT plan_noticetype FROM alarm_plans WHERE plan_id = ?", (plan_id,))
    plan_noticetypes = []
    if is_string_valid(plan_noticetype):
        plan_noticetypes = plan_noticetype.split(',')
    if plan_email == 1 and 'email' not in plan_noticetypes:
        plan_noticetypes.append('email')
    elif plan_email == 0 and 'email' in plan_noticetypes:
        plan_noticetypes.remove('email')
    plan_noticetype = ','.join(plan_noticetypes)
    execute("UPDATE alarm_plans SET plan_noticetype = ? WHERE plan_id = ?", (plan_noticetype, plan_id))
    return { 'status': 'ok', 'data': 'success' }

@alarm_plans_bp.route('/api/delete_alarm_plan', methods=['POST'])
@jwt_required()
def delete_alarm_plan():
    plan_id = request.json.get('plan_id')
    execute("DELETE FROM alarm_plans WHERE plan_id = ?", (plan_id,))
    return { 'status': 'ok', 'data': 'success' }

@alarm_plans_bp.route('/api/test_alarm_template', methods=['POST'])
@jwt_required()
def test_alarm_template():
    plan_id = request.json.get('plan_id')
    plan_name = request.json.get('plan_name')
    plan_maxtime = int(request.json.get('plan_maxtime'))
    plan_rangetime = int(request.json.get('plan_rangetime'))
    plan_maxcount = int(request.json.get('plan_maxcount'))
    plan_begintime = request.json.get('plan_begintime')
    plan_endtime = request.json.get('plan_endtime')
    plan_template = request.json.get('plan_template')
    alarm_type = request.json.get('alarm_type')
    message = render_alarm_template({
        'alarm_type': alarm_type,
        'plan_maxcount': plan_maxcount,
        'plan_maxtime': plan_maxtime,
        'plan_rangetime': plan_rangetime,
        'plan_begintime': plan_begintime,
        'plan_endtime': plan_endtime,
        'plan_name': plan_name,
        'plan_id': plan_id,
        'plan_count': '2024-12-22 14:58:17,2024-12-22 16:20:33',
        'offlinetime': '2024-12-22 14:58:17',
        'client_id': 'testdeviceid0001',
        'client_name': '测试设备',
        'client_ip': '11.11.11.11',
        'plan_template': plan_template
    })
    return { 'status': 'ok', 'data': message }
